package com.yusiji.sqlSession;

import com.yusiji.config.BoundSql;
import com.yusiji.pojo.Configuration;
import com.yusiji.pojo.MapperStatement;
import com.yusiji.utils.GenericTokenParser;
import com.yusiji.utils.ParameterMapping;
import com.yusiji.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yusiji
 */
public class SimpleExecutor implements Executor{
    @Override
    public <E> List<E> query(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {

        PreparedStatement preparedStatement = getSqlPreparedStatement(configuration,mapperStatement,params);

        ResultSet resultSet = preparedStatement.executeQuery();

        String resultType = mapperStatement.getResultType();

        Class<?> resultTypeClass = getClassType(resultType);


        ArrayList<Object> objects = new ArrayList<>();
        while(resultSet.next()){
            Object o1 = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int j = 1; j <= metaData.getColumnCount() ; j++) {
                String columnName = metaData.getColumnName(j);
                Object object = resultSet.getObject(columnName);

                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o1,object);
            }
            objects.add(o1);
        }
        return (List<E>) objects;


    }

    @Override
    public Integer update(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {
        PreparedStatement preparedStatement = getSqlPreparedStatement(configuration,mapperStatement,params);
        int resultSet = preparedStatement.executeUpdate();
        return resultSet;
    }

    @Override
    public Integer insert(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {
        return update(configuration,mapperStatement,params);
    }

    @Override
    public Integer delete(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {
        return update(configuration,mapperStatement,params);
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if(paramterType !=null){
            Class<?> aClass =  Class.forName(paramterType);
            return aClass;
        }
        return null;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse,parameterMappings);


        return boundSql;
    }

    private PreparedStatement getSqlPreparedStatement(Configuration configuration, MapperStatement mapperStatement, Object... params) throws Exception {

        Connection connection = configuration.getDataSource().getConnection();

        String sql = mapperStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

        List<ParameterMapping> paramterMappingList = boundSql.getParamterMappingList();

        String paramterType = mapperStatement.getParamterType();
        Class<?> paramterTypeClass = getClassType(paramterType);
        for (int i = 0; i < paramterMappingList.size(); i++) {
            ParameterMapping parameterMapping = paramterMappingList.get(i);
            String content = parameterMapping.getContent();

            Field declaredField = paramterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        return  preparedStatement;
    }
}
